var config = require('../config')
var constant = require('./constant')
var login = require('./login')

/**统一HTTP请求接口
 * url:需要请求的路径(必填)
 * options:请求的参数(选填)
 * callback:请求完成之后的回调(必填例:function(res){})
 * method:请求方式get/post(必填)
*/
var request = function(url,options,callback,method) {
    // wx.showLoading({
    //   title: '加载中...',
    //   mask: true
    // });
    var data = {},contentType = 'application/json';
    if(typeof options == 'function'){
        method = callback;
        callback = options;
    }else{
        data = options;
    }
    if (url.indexOf("http") != 0) {
        url = `${config.BASE_PATH}${url}`;
    }
    if(method=='get'){
        contentType = 'application/json';
    }else if(method=='post'){
        contentType = 'application/x-www-form-urlencoded';
    }
    wx.request({
        url: url,
        data: data,
        method: method,
        header: { "content-type": contentType, "loginToken": wx.getStorageSync(constant.LOGIN_TOKEN)},
        mask: 'true',
        complete: function (res) {
            wx.hideLoading();
            //用户未登录或者服务端登录态失效则直接重新登录然后
          if (res.data.flag == 401 && typeof callback == 'function'){
              wx.showLoading();
              login.login(function () {
                setTimeout(() => {
                  wx.hideLoading();
                }, 100);  
                request(url, options, callback, method)
              }, function () {
                wx.showModal({
                  title: '温馨提示',
                  content: '服务器异常！',
                  showCancel: false,
                  complete: function (res) {
                    if (res.confirm) {
                      wx.redirectTo({
                        url: '/pages/404/404'
                      });
                    }
                  }
                });
              });
            } else if (res.statusCode == '200' && typeof callback == 'function') {
                callback(res);
            }else {
              wx.showModal({
                title: '温馨提示',
                content: '服务器异常!',
                showCancel: false,
                complete: function (res) {
                  if (res.confirm) {
                    wx.redirectTo({
                      url: '/pages/404/404',
                    });
                  }
                }
              });
            }
        }
    });
}

module.exports = {
    request: request
}